package base

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/rpc/forumclient"
	"mall/service/product/rpc/productclient"
	"mall/service/promotion/rpc/promotionclient"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type InitDatabaseLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewInitDatabaseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InitDatabaseLogic {
	return &InitDatabaseLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InitDatabaseLogic) InitDatabase() (resp *types.BaseMsgResp, err error) {
	res, err := l.svcCtx.AttachmentRpc.BackendGetAttachmentLogList(l.ctx, &attachmentclient.AttachmentLogListReq{
		PageSize: uint64(50),
		RMQStep:  pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		logx.Errorw("ScanAttachmentLogDeletedProcessor err", logx.Field("detail", err.Error()))
		return nil, err
	}
	var blogIds []string
	var forumIds []string
	var userIds []string
	var productIds []string
	var promotionIds []string
	var ids []uint64
	var idMap = make(map[uint64]struct{})
	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.ObjectId != nil && *v.ObjectId > 0 && v.ObjectType != nil && *v.ObjectType > 0 {
				objectType := int32(*v.ObjectType)
				switch objectType {
				case globalkey.AttachmentLogTypePage, globalkey.AttachmentLogTypeKnowledgeBase, globalkey.AttachmentLogTypePost:
					blogIds = append(blogIds, strconv.FormatUint(*v.AttachmentId, 10))
				case globalkey.AttachmentLogTypeProduct, globalkey.AttachmentLogTypeProductTerm:
					productIds = append(productIds, strconv.FormatUint(*v.AttachmentId, 10))
				case globalkey.AttachmentLogTypeForumPost, globalkey.AttachmentLogTypeForumTerm:
					forumIds = append(forumIds, strconv.FormatUint(*v.AttachmentId, 10))
				case globalkey.AttachmentLogTypeForumAvatar:
					userIds = append(userIds, strconv.FormatUint(*v.AttachmentId, 10))
				case globalkey.AttachmentLogTypePromotion, globalkey.AttachmentLogTypePromotionCoupon:
					promotionIds = append(promotionIds, strconv.FormatUint(*v.AttachmentId, 10))
				}
			}
		}
		fmt.Println("blogIds", blogIds)
		fmt.Println("productIds", productIds)
		fmt.Println("forumIds", forumIds)
		fmt.Println("userIds", userIds)
		fmt.Println("promotionIds", promotionIds)
		if len(userIds) > 0 {
			uids, err := l.getUserAttachmentLogList(userIds)
			if err != nil {
				return nil, err
			}
			if len(uids) > 0 {
				for _, v := range uids {
					if _, ok := idMap[v]; !ok {
						ids = append(ids, v)
					}
				}
			}
			fmt.Println("user", uids)
		}

		if len(blogIds) > 0 {
			bids, err := l.getBlogAttachmentLogList(blogIds)
			if err != nil {
				return nil, err
			}
			if len(bids) > 0 {
				for _, v := range bids {
					if _, ok := idMap[v]; !ok {
						ids = append(ids, v)
					}
				}
			}
			fmt.Println("blog", bids)
		}

		if len(forumIds) > 0 {
			fids, err := l.getForumAttachmentLogList(forumIds)
			if err != nil {
				return nil, err
			}
			if len(fids) > 0 {
				for _, v := range fids {
					if _, ok := idMap[v]; !ok {
						ids = append(ids, v)
					}
				}
			}
			fmt.Println("forum", fids)
		}

		if len(productIds) > 0 {
			pids, err := l.getProductAttachmentLogList(productIds)
			if err != nil {
				return nil, err
			}
			if len(pids) > 0 {
				for _, v := range pids {
					if _, ok := idMap[v]; !ok {
						ids = append(ids, v)
					}
				}
			}
			fmt.Println("product", pids)
		}

		if len(promotionIds) > 0 {
			pids, err := l.getPromotionAttachmentLogList(promotionIds)
			if err != nil {
				return nil, err
			}
			if len(pids) > 0 {
				for _, v := range pids {
					if _, ok := idMap[v]; !ok {
						ids = append(ids, v)
					}
				}
			}
			fmt.Println("promotion", pids)
		}

		fmt.Println("ids:", ids)
	}

	//todo:删除att log
	if len(ids) > 0 {
		_, err := l.svcCtx.AttachmentRpc.BackendDeleteAttachmentLog(l.ctx, &attachmentclient.IDsReq{
			Ids: ids,
		})
		if err != nil {
			return nil, err
		}
	}

	return nil, nil
}

func (l *InitDatabaseLogic) getUserAttachmentLogList(ids []string) ([]uint64, error) {
	//orderStr := pointy.GetPointer("id:1")
	//orderBys := util.ParseSorter(orderStr)
	res, err := l.svcCtx.UserRpc.BackendGetAttachmentLogList(l.ctx, &userclient.BackendAttachmentLogListReq{
		Ids: pointy.GetPointer(strings.Join(ids, ",")),
		//OrderBy  :orderBys,
	})
	if err != nil {
		return nil, err
	}
	var rids []uint64
	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.Id != nil && *v.Id > 0 {
				rids = append(rids, *v.Id)
			}
		}
	}
	return rids, nil
}

func (l *InitDatabaseLogic) getBlogAttachmentLogList(ids []string) ([]uint64, error) {
	//orderStr := pointy.GetPointer("id:1")
	//orderBys := util.ParseSorter(orderStr)
	res, err := l.svcCtx.BlogRpc.BackendGetAttachmentLogList(l.ctx, &blogclient.BackendAttachmentLogListReq{
		Ids: pointy.GetPointer(strings.Join(ids, ",")),
		//OrderBy  :orderBys,
	})
	if err != nil {
		return nil, err
	}
	var rids []uint64
	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.Id != nil && *v.Id > 0 {
				rids = append(rids, *v.Id)
			}
		}
	}
	return rids, nil
}

func (l *InitDatabaseLogic) getForumAttachmentLogList(ids []string) ([]uint64, error) {
	//orderStr := pointy.GetPointer("id:1")
	//orderBys := util.ParseSorter(orderStr)
	res, err := l.svcCtx.ForumRpc.BackendGetAttachmentLogList(l.ctx, &forumclient.BackendAttachmentLogListReq{
		Ids: pointy.GetPointer(strings.Join(ids, ",")),
		//OrderBy  :orderBys,
	})
	if err != nil {
		return nil, err
	}
	var rids []uint64
	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.Id != nil && *v.Id > 0 {
				rids = append(rids, *v.Id)
			}
		}
	}
	return rids, nil
}

func (l *InitDatabaseLogic) getProductAttachmentLogList(ids []string) ([]uint64, error) {
	//orderStr := pointy.GetPointer("id:1")
	//orderBys := util.ParseSorter(orderStr)
	res, err := l.svcCtx.ProductRpc.BackendGetAttachmentLogList(l.ctx, &productclient.BackendAttachmentLogListReq{
		Ids: pointy.GetPointer(strings.Join(ids, ",")),
		//OrderBy  :orderBys,
	})
	if err != nil {
		return nil, err
	}
	var rids []uint64
	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.Id != nil && *v.Id > 0 {
				rids = append(rids, *v.Id)
			}
		}
	}
	return rids, nil
}

func (l *InitDatabaseLogic) getPromotionAttachmentLogList(ids []string) ([]uint64, error) {
	//orderStr := pointy.GetPointer("id:1")
	//orderBys := util.ParseSorter(orderStr)
	res, err := l.svcCtx.PromotionRpc.BackendGetAttachmentLogList(l.ctx, &promotionclient.BackendAttachmentLogListReq{
		Ids: pointy.GetPointer(strings.Join(ids, ",")),
		//OrderBy  :orderBys,
	})
	if err != nil {
		return nil, err
	}
	var rids []uint64
	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.Id != nil && *v.Id > 0 {
				rids = append(rids, *v.Id)
			}
		}
	}
	return rids, nil
}
